<!-- src/views/login/Login.vue -->
<template>
  <div>
    <el-form
        :model="loginForm"
        :rules="rules"
        ref="loginForm"
        label-width="100px"
        class="login-form"
    >
      <h3 class="login-title">超市账单管理系统</h3>

      <el-form-item label="账号" prop="userCode">
        <el-input v-model="loginForm.userCode" />
      </el-form-item>

      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password" />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm">登录</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
// import axios from 'axios'
// import { server_url } from '@/utils/server'
import { login } from '@/api/user'

export default {
  name: 'LoginPage',
  data() {
    return {
      loginForm: {
        userCode: '',
        password: ''
      },
      rules: {
        userCode: [
          { required: true, message: '请输入账号名', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    submitForm() {
      this.$refs.loginForm.validate((valid) => {
        if (!valid) return

        // const params = new URLSearchParams({
        //   userCode: this.loginForm.userCode,
        //   passWord: this.loginForm.password
        // })

        // 使用导入的 API 函数
        login(this.loginForm.userCode, this.loginForm.password)
            .then((resp) => {
              // 现在 resp 是完整的响应对象，我们需要获取 data 字段
              const responseData = resp.data;
              console.log('登录响应数据:', responseData);
              
              if (responseData.flag) {
                localStorage.setItem(
                    'loginUser',
                    JSON.stringify(responseData.data)
                )
                this.$router.replace('/homepage')
              } else {
                this.$message.error(responseData.message || '登录失败')
              }
            })
            .catch((err) => {
              this.$message.error('网络或服务器错误')
              console.error(err)
            })
      })
    },
    resetForm() {
      this.$refs.loginForm.resetFields()
    }
  }
}
</script>

<style scoped>
.login-form {
  width: 450px;
  height: 220px;
  border: 1px solid #DCDFE6;
  border-radius: 5px;
  box-shadow: 0 0 25px #909399;
  margin: 150px auto;
  padding: 35px 35px 15px 35px;
}
.login-title {
  text-align: center;
  margin: 0 auto 10px auto;
  color: #303133;
}
</style>
